/**
 * Mock Context Manager Service
 * 端口: 4000
 * 模拟上下文管理器，用于测试
 */

const express = require('express');
const app = express();
app.use(express.json());

const PORT = 4000;

// 内存存储
const sessions = new Map();

/**
 * 获取会话消息
 * POST /messages/get
 */
app.post('/messages/get', (req, res) => {
  const { sessionId, agentId, limit = 10, offset = 0 } = req.body;

  console.log(`[ContextManager] Getting messages for session: ${sessionId}`);

  const sessionKey = `${agentId}:${sessionId}`;
  let messages = sessions.get(sessionKey) || [];

  // 分页
  const paginatedMessages = messages.slice(offset, offset + limit);

  res.json({
    sessionId,
    messages: paginatedMessages,
    totalCount: messages.length,
    hasMore: messages.length > offset + limit
  });
});

/**
 * 添加消息
 * POST /messages/add
 */
app.post('/messages/add', (req, res) => {
  const { sessionId, agentId, message } = req.body;

  console.log(`[ContextManager] Adding message to session: ${sessionId}`);
  console.log(`  Role: ${message.role}, Content: ${message.content?.substring(0, 50)}...`);

  const sessionKey = `${agentId}:${sessionId}`;
  let messages = sessions.get(sessionKey) || [];

  // 添加时间戳和ID
  const messageWithMeta = {
    id: `msg-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
    timestamp: new Date().toISOString(),
    ...message
  };

  messages.push(messageWithMeta);
  sessions.set(sessionKey, messages);

  res.json({
    success: true,
    messageId: messageWithMeta.id
  });
});

/**
 * 健康检查
 * GET /health
 */
app.get('/health', (req, res) => {
  res.json({
    status: 'ok',
    service: 'mock-context-manager',
    port: PORT,
    activeSessions: sessions.size
  });
});

/**
 * 清空会话（测试辅助）
 * DELETE /sessions/:sessionId
 */
app.delete('/sessions/:sessionId', (req, res) => {
  const { sessionId } = req.params;
  let deleted = 0;

  for (const [key, value] of sessions.entries()) {
    if (key.includes(sessionId)) {
      sessions.delete(key);
      deleted++;
    }
  }

  console.log(`[ContextManager] Deleted ${deleted} sessions matching: ${sessionId}`);
  res.json({ success: true, deleted });
});

/**
 * 获取所有会话（调试）
 * GET /debug/sessions
 */
app.get('/debug/sessions', (req, res) => {
  const allSessions = {};
  for (const [key, messages] of sessions.entries()) {
    allSessions[key] = {
      messageCount: messages.length,
      lastMessage: messages[messages.length - 1]
    };
  }
  res.json(allSessions);
});

// 启动服务
app.listen(PORT, () => {
  console.log('================================================');
  console.log('🎭 Mock Context Manager Service');
  console.log(`📡 Port: ${PORT}`);
  console.log(`🔗 URL: http://localhost:${PORT}`);
  console.log('================================================');
  console.log('');
  console.log('Available endpoints:');
  console.log('  POST /messages/get    - Get session messages');
  console.log('  POST /messages/add    - Add message to session');
  console.log('  GET  /health          - Health check');
  console.log('  DELETE /sessions/:id  - Clear session (test helper)');
  console.log('  GET  /debug/sessions  - Debug view');
  console.log('');
});

// 优雅关闭
process.on('SIGTERM', () => {
  console.log('\n[ContextManager] Shutting down gracefully...');
  process.exit(0);
});
